package com.dreamer.service.socket;

import com.dreamer.domain.socket.ChatGroup;
import com.dreamer.domain.socket.Message;
import com.dreamer.domain.user.User;
import com.dreamer.service.mobile.ChatGroupHandler;
import com.dreamer.service.mobile.NoticeHandler;
import com.dreamer.service.mobile.SocketMessageHandler;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class MessageHandler extends TextWebSocketHandler {

//    @Autowired
//    private RedisDao redisDao;

    @Autowired
    private SocketMessageHandler socketMessageHandler;

    @Autowired
    private NoticeHandler noticeHandler;

    @Autowired
    private ChatGroupHandler chatGroupHandler;


    private final static Map<Integer, WebSocketSession> SESSION_MAP;

    static {
        SESSION_MAP = new ConcurrentHashMap<>();
    }


    //获取当前sessionMap
    private Map<Integer, WebSocketSession> getSessionMap() {
//        Map<Integer, WebSocketSession> SESSION_MAP = redisDao.getObject("SESSION_MAP", Map.class);
//        if (SESSION_MAP == null) {
//            SESSION_MAP = new HashedMap();
//            redisDao.putObject("SESSION_MAP", SESSION_MAP);
//        }
        return SESSION_MAP;
    }

    //获取当前session
    private WebSocketSession currentSession(Integer userId) {
        System.out.println(getSessionMap().size() + "当前连接人数");
        if (getSessionMap().containsKey(userId)) {//在线
            WebSocketSession socketSession = getSessionMap().get(userId);
            if (socketSession.isOpen()) {//在线
                return socketSession;
            } else {//不在线
                System.out.println(userId + "接收方在线但是没打开！");//TODO 不在线本地化存储
            }
        } else {
            System.out.println(userId + "接收方不在线！");//TODO 不在线本地化存储

        }
        return null;
    }

    //保存当前session
    private void saveSession(Integer userId, WebSocketSession socketSession) {
        getSessionMap().put(userId, socketSession);
    }

    private User getUser(WebSocketSession session) {
        User user = (User) session.getAttributes().get("user");
        return user;
    }


    //建立连接后
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        try {
        User user = getUser(session);
        System.out.println(user.getId() + "当前登录的用户");
        Integer userId = user.getId();
        saveSession(userId, session);//存储当前
        //取出当前用户没有收到的所有消息然后发送
        Map<String,Object> map = new HashMap<>();
        map.put("toId",String.valueOf(userId));
        map.put("send",false);
        List<Message> messages = socketMessageHandler.getList(map);
        if(messages.isEmpty())return;
        JSONArray object = JSONArray.fromObject(messages);
        session.sendMessage(new TextMessage(object.toString()));//发送
        for (Message message : messages) {
            message.setSend(true);
            socketMessageHandler.merge(message);//设置为已读取
        }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //发送消息
        String text = message.getPayload();
        System.out.println("收到的消息是" + text);
        try {
            JSONObject json = JSONObject.fromObject(text);
            Message message1 = (Message) JSONObject.toBean(json, Message.class);
            String toId = message1.getToId();
            System.out.println("发送方是" + message1.getFromId());
            System.out.println("接收方是" + message1.getToId());
            System.out.println("消息是" + message1.getMsg());
            if (toId.contains("group")) {//如果是发到群里
                //取出所有群的人 逐个发送
            } else {//如果是发给个人
                User user = getUser(session);

                //如果不是群聊 TODO 这里判断
                if(toId.indexOf("G")>-1){//是群聊
                    toId = toId.replace("G","");
                    Integer gid = Integer.valueOf(toId);
                    ChatGroup chatGroup = chatGroupHandler.get(gid);//获取群信息
                    if(chatGroup==null)return;
                    String uids = chatGroup.getUids();
                    for(String uid:uids.split("\\+")){
                        Integer id = Integer.valueOf(uid);
                        System.out.println(id+"+="+user.getId());
                        if(id.equals(user.getId()))continue;//不给自己发送
                        Message message2 = (Message) JSONObject.toBean(json, Message.class);
                        message2.setFromId("G"+gid);
//                        message2.setAvatar(chatGroup.getAvatar());
                        message2.setCode(""+chatGroup.getId());
                        TextMessage textMessage = new TextMessage(JSONObject.fromObject(message2).toString());

                        WebSocketSession toSession = currentSession(Integer.valueOf(id));
                        if (toSession != null) {
                            toSession.sendMessage(textMessage);
                        }else {  //TODO 暂时不本地存储
                           saveMessage(message2);
                        }
                    }
                }else {
                    WebSocketSession toSession = currentSession(Integer.valueOf(toId));
                    if (toSession != null) {
                        toSession.sendMessage(message);
                    } else {
                        saveMessage(message1);
                    }
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void saveMessage(Message message){

        Runnable runnable = ()->{
            //TODO 对方不在线持久化存储
            message.setSend(false);//设置未读
            socketMessageHandler.merge(message);
            //离线通知客户 异步的
            try {
                noticeHandler.noticeMessage(message);
            }catch (Exception e){
                e.printStackTrace();
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();

    }


    public static void main(String[] args) {
        String s = "{\"fromId\":\"60115\",\"toId\":\"118013\",\"avatar\":\"http://wx.qlogo.cn/mmopen/9rFLdoky60dReLAoa4kQ8wCWibmmsgGqKkoJ5BhkQRpzQUV3Eo10VM6lsIP6ZZZTnsrHJeEViavRV7xdL2IhpYKXnUIMJFxA7J/0\",\"msg\":\"安师大\"}";
        JSONObject jsonObject = JSONObject.fromObject(s);
        System.out.println(jsonObject.toString());
        Message message = (Message) JSONObject.toBean(jsonObject, Message.class);
        System.out.println(message.getFromId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        User user = getUser(session);
        //移除当前
        getSessionMap().remove(user.getId());
        System.out.println("掉线移除！！" + user.getId());
    }



}
